package isi_ib;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;

import utiles_isi.dateutil;
import utiles_isi.isi_conexion;

import com.ib.client.Contract;
import com.ib.client.EClientSocket;

public class historico_ib {
	
	int tickerId;
	private Contract contract;
	private String endDateTime; //yyyymmdd hh:mm:ss
	private String durationStr; //S D W M Y
	private String barSizeSetting;//1 sec, 5 secs,15 secs,30 secs,1 min,2 mins,3 mins,5 mins,15 mins,30 mins,1 hour,1 day
	private String whatToShow;	// TRADES,MIDPOINT,BID,ASK,	BID_ASK,HISTORICAL_VOLATILITY,OPTION_IMPLIED_VOLATILITY
	private int useRTH;
	//0 - all data is returned even where the market in question was outside of its regular trading hours.
	//1 - only data within the regular trading hours is returned, even if the requested time span falls partially or completely outside of the RTH.
	private int formatDate;
//	1 - dates applying to bars returned in the format:	yyyymmdd{space}{space}hh:mm:dd
//	2 - dates are returned as a long integer specifying the number of seconds since 1/1/1970 GMT.
	
	public historico_ib() {
		super();
		setHistorico_ib(0,null,"","","");
		
	}
	
	public historico_ib(int tickerId, Contract contract, String endDateTime,
			String durationStr, String barSizeSetting) {
		super();
		setHistorico_ib(tickerId,contract,endDateTime,durationStr,barSizeSetting);
	}
	
	public void setHistorico_ib(int tickerId, Contract contract, String endDateTime,
			String durationStr, String barSizeSetting) {
		setTickerId(tickerId);
		setFormatDate(2);
		setUseRTH(1);
		this.contract = contract;
		this.endDateTime = endDateTime;
		this.durationStr = durationStr;
		this.barSizeSetting = barSizeSetting;
		setWhatToShow("TRADES"); 
	}
	
	public int getTickerId() {
		return tickerId;
	}
	
	public void setTickerId(int tickerId) {
		if(tickerId==0)
		{
			Random randomGenerator = new Random();
			tickerId=randomGenerator.nextInt(100000000);
		}
		this.tickerId = tickerId;
	}
	public Contract getContract() {
		return contract;
	}
	public void setContract(Contract contract) {
		this.contract = contract;
	}
	public String getEndDateTime() {
		if(endDateTime.isEmpty()) 
				{
			       if(formatDate==2)return String.valueOf(System.currentTimeMillis()/1000);
			       else  return  dateutil.now("yyyyMMdd HH:mm:ss z");
				
				}
		else return endDateTime;
	}
	public void setEndDateTime(String endDateTime) {
		this.endDateTime = endDateTime;
	}
	public String getDurationStr() {
		//S D W M Y
		if (durationStr.isEmpty()) return ("1 D");
		else return durationStr;
	}
	public void setDurationStr(String durationStr) {
		this.durationStr = durationStr;
	}
	public void setDurationStr(String cant_,String period_) {
		this.durationStr = cant_+" "+period_;
	}
	public String getBarSizeSetting() {
		if(barSizeSetting.isEmpty()) return "5 mins";
		else	return barSizeSetting;
	}
	public void setBarSizeSetting(String barSizeSetting) {
		this.barSizeSetting = barSizeSetting;
	}
	public String getWhatToShow() {
		return whatToShow;
	}
	public void setWhatToShow(String whatToShow) {
		this.whatToShow = whatToShow;
	}
	public int getUseRTH() {
		return useRTH;
	}
	public void setUseRTH(int useRTH) {
		this.useRTH = useRTH;
	}
	public int getFormatDate() {
		return formatDate;
	}
	public void setFormatDate(int formatDate) {
		this.formatDate = formatDate;
	}
	public int getPeriodo(){
		int m_=1;
		String[] tokens = barSizeSetting.split(" ");
		if (tokens[1].contains("sec")){	m_=1;}else
			if (tokens[1].contains("min")){	m_=60;}else
					if (tokens[1].contains("hour")){m_=3600;}else
						if (tokens[1].contains("min")){m_=3600*24;}
		
		return m_* Integer.parseInt(tokens[0]);
	}
	public  void registra(){
		
		isi_conexion con= new isi_conexion("");
		if(!con.Active()) con.conecta();

		String sql_=" REPLACE INTO isitrader.tiker_peticiones (`reqId`, `endDateTime`, `durationStr`, `barSizeSetting`, `whatToShow`, `useRTH`, `formatDate`,`contrato`,`periodo`) VALUES " +
	    		"('" +
	    		getTickerId()+"','"+
	    		getEndDateTime()+"','"+
	    		getDurationStr()+"','"+
	    		getBarSizeSetting()+"','"+
	    		getWhatToShow()+"','"+
	    		getUseRTH()+"','"+
	    		getFormatDate()+"','"+
	    		contract.m_symbol+"','"+
	    		String.valueOf(getPeriodo())+
	    	"')";
		
		try {
			con.st.execute(sql_);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(con!=null) con.desconecta();
		
						
	}
	public void iniciaHistorico(EClientSocket   client_s){
		client_s.reqHistoricalData(tickerId,contract,getEndDateTime(),getDurationStr(),getBarSizeSetting(),getWhatToShow(),getUseRTH(),getFormatDate());
		
	}
	
	
	

	
public String toStringC(){
		
		return(
				"CONTRATO HISTORICO "+
				contract.toString()+
				"\n m_symbol->"+contract.m_symbol+
				" -- m_currency->"+contract.m_currency+
				"\n m_exchange->"+contract.m_exchange+
				" -- m_expiry->"+contract.m_expiry+
				"\n m_localSymbol->"+contract.m_localSymbol+
				" -- m_multiplier->"+contract.m_multiplier+
				"\n m_primaryExch->"+contract.m_primaryExch+
				" -- m_right->"+contract.m_right+
				"\n m_secId->"+contract.m_secId+
				" -- m_secIdType->"+contract.m_secIdType+
				"\n m_secType->"+contract.m_secType+
				" -- m_strike->"+contract.m_strike+
				"\n m_right->"+contract.m_right		
				);
	}
@Override
public String toString() {
		return "historico_ib "+"" +
				" TickerId="+ getTickerId() + 
				" -- EndDateTime=" + getEndDateTime()
				+ "\n getDurationStr=" + getDurationStr()
				+ " -- BarSizeSetting=" + getBarSizeSetting()
				+ "\n WhatToShow=" + getWhatToShow() + 
				" -- getUseRTH="+ getUseRTH() + 
				"\n formatDate=" + getFormatDate() + "\n ------------------\n"
				 + toStringC()	;
	}
	

public void Carga() throws IOException {
	    Properties prop = new Properties();
	    if((new File("historico.property")).isFile())
		{
		FileInputStream f_=new FileInputStream("historico.property");
		prop.load(f_);
		f_.close();	
		
		this.setTickerId(Integer.parseInt(prop.getProperty("TickerId","0")));
		this.setDurationStr(prop.getProperty("DurationStr","1 W"));
		this.setDurationStr(prop.getProperty("BarSizeSetting","5 mins"));
		this.setDurationStr(prop.getProperty("WhatToShow"));
		this.setDurationStr(prop.getProperty("EndDateTime",dateutil.now("yyyyMMdd HH:mm:ss z")));
				
		
		}
	    
	    
	    
		
		
	}	
	
public void Guarda() {
	    Properties prop = new Properties();
		prop.setProperty("TickerId", String.valueOf(this.getTickerId())); 
		prop.setProperty("DurationStr",this.getDurationStr());
		prop.setProperty("BarSizeSetting", this.getBarSizeSetting());
		prop.setProperty("WhatToShow", this.getWhatToShow());
		prop.setProperty("EndDateTime", this.getEndDateTime());
		
		try {
		FileOutputStream f_=new FileOutputStream("historico.property");
		prop.store(f_, null);
		f_.close();
		}catch (IOException ex) {ex.printStackTrace();}
	}
}
